/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dawnland02.model.task;

import dawnland02.model.entity.EntityInternal;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Petru Obreja (obrejap@yahoo.com)
 */
public class GroupTask extends Task{
    private final List<Task> tasks;

    private Integer currentTaskIndex = -1;
    private Task currentTask = null;

    public GroupTask(EntityInternal entity){
        this("GroupTask", entity);
    }

    public GroupTask(String name, EntityInternal entity){
        super(name, entity);
        tasks = new LinkedList<Task>();
    }

    public void addTask(Task task){
        tasks.add(task);
        task.setParentTask(this);
    }

    public List<Task> getTasks(){
        return tasks;
    }

    @Override
    public void execute() {
        if(parentTask==null){
            entity.setDuringAction(true); //start of top most task
        }
        if(getTaskStatus().compareTo(TaskStatus.PREPARED)<0){
            prepare();
        }
        if(getTaskStatus() == TaskStatus.PREPARED){
            executeNextSubtask();
        } else {
            end();
        }
    }

    @Override
    protected void prepare() {
        setTaskStatus(TaskStatus.PREPARED);
        //do nothing; it will be overwritten by subclasses
    }

    public final void executeNextSubtask(){
        if(++currentTaskIndex < tasks.size()){
            currentTask = tasks.get(currentTaskIndex);
            currentTask.execute();
        } else {
            end();
        }
    }

    @Override
    public boolean isGroupTask() {
        return true;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("(");
        if(tasks.size()>0){
            for(Task task:tasks){
                stringBuilder.append(task).append(",");
            }
            stringBuilder.deleteCharAt(stringBuilder.length()-1);
        }
        stringBuilder.append(")");
        return stringBuilder.toString();
    }

    @Override
    protected void init() {
        //do nothing; it will be overwritten by subclasses
    }

    @Override
    public void end() {
        setTaskStatus(TaskStatus.FINISHED);
        executeNextTaskFromParent();
    }
}
